# -*- coding: utf-8 -*-
from jira import JIRA
from KDissue import *
from ExcelDeal import KDExcel

def searchIssues(jql, max_results=1000):
    ''' Search issues
    @param jql: JQL, str
    @param max_results: max results, int, default 100
    @return issues: result, list
    '''
    try:
        issues = jira.search_issues(jql, maxResults=max_results)
        return issues
    except Exception as e:
        print(e)

def SearchbyJQL(jql):
    _list = []
    issues = searchIssues(jql)
    
    for issue in issues:
        # print('{0}: {1} '.format(issue.key, issue.fields.status))
        _issue         = JiraIssue()
        _content       = []
        _key           = str(issue.key)
        _type          = str(issue.fields.customfield_10700)
        _create_time   = str(issue.fields.created)
        _version       = str(issue.fields.customfield_10701 if issue.fields.customfield_10701 != None else ('' if len(issue.fields.versions) == 0 else (issue.fields.versions[0].name if len(issue.fields.versions) == 1 else issue.fields.versions[len(issue.fields.versions) - 1].name)))
        _discrip       = str(issue.fields.summary )
        # _discrip       = str(_discrip + '\n' + str(issue.fields.description) if issue.fields.description != None else '')
        _ctreater      = str(issue.fields.creator)
        _rootcause     = str(issue.fields.customfield_10600)
        _fix_discrip   = str(issue.fields.customfield_10702)
        _update_time   = str(issue.fields.updated)
        _fixVersion    = str('' if len(issue.fields.fixVersions) == 0 else (issue.fields.fixVersions[0].name if len(issue.fields.fixVersions) == 1 else issue.fields.fixVersions[len(issue.fields.fixVersions) - 1].name))
        _howtocheck    = str(issue.fields.customfield_10703)
        _handler       = str(issue.fields.assignee)
        _checkdiscrip  = str(issue.fields.customfield_10704)
        _status        = str(issue.fields.status)
        _check_time    = str(_update_time if _status == u'已关闭' else None)
        # print(_check_time)
        _updater       = str(issue.fields.reporter if _status == u'已关闭' else None)
        _result        = str(issue.fields.resolution)

        _content.append(_key)
        _content.append(_type)
        _content.append(_create_time[0:10] if _create_time != None else None)
        _content.append(_version)
        _content.append(_discrip)
        _content.append(_ctreater)
        _content.append(_rootcause)
        _content.append(_fix_discrip)
        _content.append(_update_time[0:10] if _update_time != None else None)
        _content.append(_fixVersion)
        _content.append(_howtocheck)
        _content.append(_checkdiscrip)
        _content.append(_handler)
        _content.append(_updater)
        _content.append(_result)
        _content.append(_check_time[0:10] if _check_time != None else None)
        _content.append(_status)

        _issue.insertParam(_content)
        _list.append(_issue)
        # print('****************************************************************')
    return _list


if __name__ == '__main__':
     
    m_excel = KDExcel("..\\KdIssueCollect.xlsx")

    _list = m_excel.loadCache("TeachUI")

    print("list len = ", len(_list))

    for jira_issue in _list:
        jira_issue.printparam()

    # _excel_list = m_excel.getoldsheetlist("sheet1")
    # jira = JIRA("http://192.168.1.21:8080",basic_auth=('wukai','wkwkwk1314'))

    # #************************ManageUnit(管理平台) begin***************************************
    # # search project 01
    # jql = '''
    # project = 10003 AND component = "ManageUnit(管理平台)" AND project = TSXT
    # '''
    # m_list = SearchbyJQL(jql)

    # # search project 02
    # jql = '''
    # project = 10100 AND component = "ManageUnit(管理平台)" AND project = TSXT02
    # '''
    # m_list = m_list + SearchbyJQL(jql)

    #TODO send the _list to excel deal model
    #**************************ManageUnit(管理平台) end*************************************

    # for jira_issue in m_list:
    #     for excel_issue in _excel_list:
    #         if jira_issue._discrip == excel_issue._discrip:
    #             if str(jira_issue._status) == u'已解决' or str(jira_issue._status) == u'已关闭':
    #                 print(jira_issue._key, "   has resolved or closed!")
    #                 continue
    #             Onlineissue = jira.issue(jira_issue._key)
    #             _dict = {'customfield_10600': excel_issue._rootcause, 'customfield_10702': excel_issue._fix_discrip,
    #                                          'customfield_10703': excel_issue._howtocheck, 'customfield_10704': excel_issue._checkdiscrip}
    #             print(jira_issue._key," has set ", _dict)
    #             Onlineissue.update(notify=False, fields = _dict)

    # by key
    # for jira_issue in m_list:
    #     for excel_issue in _excel_list:
    #         if jira_issue._key == excel_issue._key:
    #             if str(jira_issue._status) == u'已解决' or str(jira_issue._status) == u'已关闭':
    #                 print(jira_issue._key, "   has resolved or closed!")
    #                 continue
    #             Onlineissue = jira.issue(jira_issue._key)
    #             _dict = {'customfield_10600': str(excel_issue._discrip + '\n'+ excel_issue._rootcause), 'customfield_10702': excel_issue._fix_discrip,
    #                                          'customfield_10703': excel_issue._howtocheck, 'customfield_10704': excel_issue._checkdiscrip}
    #             print(jira_issue._key," has set ", _dict)
    #             Onlineissue.update(notify=False, fields = _dict)
    # print("update success ...")

